;; The first four lines of this file were added by Dracula.
;; They tell DrScheme that this is a Dracula Modular ACL2 program.
;; Leave these lines unchanged so that DrScheme can properly load this file.
#reader(planet "reader.rkt" ("cce" "dracula.plt") "modular" "lang")
(require "Ivolatility.lisp")
(require "M-avl-string-keys.lisp")
(require "Mhelpers.lisp")
(require "Mstock-retrieval.lisp")

(module Mvolatility
  (import Ihelpers)
  (import Itree)
  (import Istockretrieval)
  (include-book "io-utilities" :dir :teachpacks)
  
; returns the daily volatility of a stock record
(defun daily-volatility (stock)
  (let* ((opening (car (cdr stock)))
         (high (car (cddr stock)))
         (low (car (cdddr stock)))
         (closing (car (cddddr stock))))
    (/ (- high low) (/ (- closing opening) 2))))

; gives all the daily volatilites for a stock
; over a given range of dates
(defun get-all-daily-volatilities (stocks)
  (if (consp stocks)
      (cons (daily-volatility (car stocks)) (get-all-daily-volatilities (cdr stocks)))
      nil))

; returns the volatility of a stock over a range
; of dates by averaging its daily volatility
; for the given range
(defun volatility (ticker start end tree)
  (let* ((occurrences (get-stocks-in-range-by-ticker tree start end ticker))
         (daily-volatilities (get-all-daily-volatilities occurrences)))
    (list ticker (average-list daily-volatilities))))

; returns a list of pairs that all contain the name
; of a ticker and its performance in the range
(defun volatility-query-with-tickers (tickers start end tree)
  (if (consp tickers)
      (cons (volatility (car tickers) start end tree) (volatility-query-with-tickers (cdr tickers) start end tree))
      nil))

; returns the maximum of all the volatilities returned
; using get-max
(defun volatility-query (start end tickers tree)
  (if (consp tickers)
      (let* ((volatilities (volatility-query-with-tickers tickers start end tree))
             (best (get-max volatilities (car volatilities))))
        (concatenate 'string (car best) ": " (rat->str (* 100 (cadr best)) 1) "%"))
      (let* ((volatilities (volatility-query-with-tickers (get-all-tickers (get-stocks-in-range tree start end)) start end tree))
             (best (get-max volatilities (car volatilities))))
        (concatenate 'string (car best) ": " (rat->str (* 100 (cadr best)) 1) "%"))))
  
 (export Ivolatility))